package com.gowants.pems.util;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;

/**
 * <文件下载>
 *
 * @ClassName DownLoadUtil
 * @remake create by GJR 2019/6/15 12:12
 */
public class DownLoadUtil
{

    /**
     * <支持在线打开预览文件下载>
     *
     * @param
     * @return
     * @remake create by GJR 2019/6/15 12:17
     */
    public static void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception
    {
        File f = new File(filePath);
        if (!f.exists())
        {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        // 重置响应对象， 非常重要
        response.reset();
        // 在线打开方式
        if (isOnLine)
        {
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType()+";charset=utf-8");
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
        }
        // 纯下载方式
        else
        {
        	 String filename = new String(f.getName().getBytes(), "ISO-8859-1");
             response.setContentType("application/x-msdownload;charset=utf-8");
             response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
//            response.setContentType("application/x-msdownload");
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }

        OutputStream out = response.getOutputStream();

        while ((len = br.read(buf)) > 0)
        {
            out.write(buf, 0, len);
        }

        br.close();
        out.close();
    }

    public static void main(String[] args) throws Exception
    {
        URL u = new URL("http://www.baidu.com");
        System.out.println(u.toString());
        URLConnection openConnection = u.openConnection();
        String contentType = openConnection.getContentType();
        System.out.println();
//        StringBuilder sb = new StringBuilder();
        //String s = "abcdefg";
//        sb.append(s);
//        sb.reverse();
//        System.out.println(sb);
//        System.out.println(s.charAt(2));
        
        //System.out.println(reverseStr(s));
        
        InetAddress addr = InetAddress.getLocalHost();
        
        System.out.println(addr.getLoopbackAddress());
    }
    public static String reverseStr(String str){
        if(str.length() <= 1){
            return str;
        }
        return reverseStr(str.substring(1)) + str.charAt(0);
    }
}
